//
//  KLSGDetailProgramAndSpeakController.m
//  KaoLaShiGuangFM
//
//  Created by lanou3g on 15/10/29.
//  Copyright © 2015年 com.lanou3g. All rights reserved.
//

#import "KLSGDetailProgramAndSpeakController.h"
#import "KLSGBfifSpeakView.h"
#import "KLSGVoiceCell.h"
#import "KLSGAlbumCell.h"
#import "KLSGVoiceModel.h"
#import "KLSGAlbumModel.h"
#import "KLSGAlbumController.h"
#import "KLSGBrifAndVoiceViewController.h"
#import "KLSGBrifSpeakController.h"

@interface KLSGDetailProgramAndSpeakController ()

@property (nonatomic, strong) NSMutableDictionary *dataDic;
@property (nonatomic, strong) KLSGBfifSpeakView *BfifSpeakView;
@property (nonatomic, strong) NSMutableArray *dataVoiceArray;
@property (nonatomic, strong) NSMutableArray *dataAlbumArray;
@property (nonatomic, assign) NSInteger pageId;
@property (nonatomic, assign) NSInteger pageCount;

@end

@implementation KLSGDetailProgramAndSpeakController


- (instancetype)initWithStyle:(UITableViewStyle)style
{
    if (self = [super initWithStyle:UITableViewStyleGrouped]) {
        
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.tableView.bounces = NO;
    [self addNavigationBar];
    self.tableView.showsVerticalScrollIndicator = NO;
    [self.tableView registerClass:[KLSGAlbumCell class] forCellReuseIdentifier:@"reuseIdentifier"];
    [self.tableView registerClass:[KLSGVoiceCell class] forCellReuseIdentifier:@"voliceCELL"];
    
    self.tableView.contentInset = UIEdgeInsetsMake(170, 0, 0, 0);
    [self setUpData];
    _pageId = 1;
    [self voiceData];
    [self albumData];
    [self addBrifSpeakView];
    [self.tableView setSeparatorStyle:(UITableViewCellSeparatorStyleNone)];
}

- (void)addNavigationBar
{
    self.navigationController.title = [self.dataDic valueForKey:@"nickname"];;
    UIBarButtonItem *left = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:(UIBarButtonSystemItemReply) target:self action:@selector(leftReturn)];
    self.navigationItem.leftBarButtonItem = left;
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor colorWithRed:234 / 256.0 green:79 / 256.0 blue:56 / 256.0 alpha:1];
}
- (void)leftReturn
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)addBrifSpeakView
{
    self.BfifSpeakView = [[KLSGBfifSpeakView alloc] initWithFrame:CGRectMake(0, -(170), kScreenWidth, 170)];
    [self.tableView addSubview:self.BfifSpeakView];
} 

- (void)addUI
{
    [self.BfifSpeakView.speakImage sd_setImageWithURL:[NSURL URLWithString:[self.dataDic valueForKey:@"mobileLargeLogo"]] placeholderImage:[UIImage imageNamed:@"zhanweitu"]];
    [self.BfifSpeakView.bgImageView sd_setImageWithURL:[NSURL URLWithString:[self.dataDic valueForKey:@"backgroundLogo"]] placeholderImage:[UIImage imageNamed:@"zhanweitu"]];
    self.BfifSpeakView.nameLable.text = [self.dataDic valueForKey:@"nickname"];
    self.BfifSpeakView.brifLable.text = [self.dataDic valueForKey:@"personalSignature"];
    [self.BfifSpeakView.button addTarget:self action:@selector(brifButton) forControlEvents:(UIControlEventTouchUpInside)];
    
    UITapGestureRecognizer *tapGeature = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(brifButton)];
    [self.BfifSpeakView.bgImageView addGestureRecognizer:tapGeature];
    
}
- (void)brifButton
{
    KLSGBrifSpeakController *brifVC = [[KLSGBrifSpeakController alloc] init];
    brifVC.modalTransitionStyle = UIModalTransitionStylePartialCurl;
    brifVC.dic = self.dataDic;
    [self presentViewController:brifVC animated:YES completion:nil];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 1) {
        return self.dataVoiceArray.count;
    } else {
        if (self.dataAlbumArray.count >= 2) {
            return 2;
        }
    }
    return self.dataAlbumArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1) {
        KLSGVoiceCell *cell = [tableView dequeueReusableCellWithIdentifier:@"voliceCELL" forIndexPath:indexPath];
        if (self.dataVoiceArray.count > 0) {
            KLSGVoiceModel *model = self.dataVoiceArray[indexPath.row];
            cell.titleLable.text = model.title;
            cell.nickNameLable.text = model.nickname;
            cell.likesLable.text = [NSString stringWithFormat:@"%@", model.likes];
            cell.playTimesLable.text = [NSString stringWithFormat:@"%@", model.playtimes];
            [cell.logoImage sd_setImageWithURL:[NSURL URLWithString:model.coverMiddle] placeholderImage:[UIImage imageNamed:@"zhanweitu"]];
        }
        
        return cell;
    } else {
        KLSGAlbumCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuseIdentifier" forIndexPath:indexPath];
        if (self.dataAlbumArray.count > 0) {
            KLSGAlbumModel *model = self.dataAlbumArray[indexPath.row];
            [cell.coverSmallImage sd_setImageWithURL:[NSURL URLWithString:model.coverSmall] placeholderImage:[UIImage imageNamed:@"zhanweitu"]];
            cell.titleLable.text = model.title;
            cell.tracksLable.text = [NSString stringWithFormat:@"%@集", model.tracks];
            CGFloat pTimes = [model.playTimes intValue];
            cell.playTimesLable.text = [NSString stringWithFormat:@"%.1f万", pTimes / 10000];
            
            CGFloat updateAt = [model.updatedAt floatValue];
            cell.updataAtLable.text = [NSString stringWithFormat:@"最后更新于%f天前", updateAt];
            [cell.collectButton addTarget:self action:@selector(actionCollect:) forControlEvents:(UIControlEventTouchUpInside)];
        }
        
        return cell;
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 40;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        KLSGAlbumModel *model = self.dataAlbumArray[indexPath.row];
        KLSGBrifAndVoiceViewController *BAVVC = [[KLSGBrifAndVoiceViewController alloc] init];
        BAVVC.albumIdString = [NSString stringWithFormat:@"%@", model.albumId];
        KLSGKindModel *kindModel = [[KLSGKindModel alloc] init];
        kindModel.albumCoverUrl290 = model.coverSmall;
        kindModel.albumId = model.albumId;
        kindModel.title = model.title;
        kindModel.playsCounts = model.playTimes;
        kindModel.tracksCounts = model.tracks;
        BAVVC.model = kindModel;
        [self.navigationController pushViewController:BAVVC animated:YES];
    } else {
        AppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
        KLSGPlayRadioViewController *playViewController = (KLSGPlayRadioViewController *)appDelegate.playVC;
        // 根据位置得到model
        KLSGVoiceModel *model = self.dataVoiceArray[indexPath.row];
        // 电台标题
        playViewController.rname = model.title;
        // radioModel数组
        playViewController.radioModelArray = self.dataVoiceArray;
        // 获取当前点击下标
        playViewController.index = indexPath.row;
        // id
        playViewController.radioId = model.trackId;
        playViewController.voiceModel =  model;
        playViewController.type = VoiceTypeVoice;
        [self presentViewController:playViewController animated:YES completion:nil];
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 50)];
    view.backgroundColor = [UIColor lightGrayColor];
    view.alpha = kAlpha;
    
    UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(20, 0, 200, 40)];
    lable.alpha = kAlpha;
    [view addSubview:lable];
    
    if (section == 0) {
        lable.text = [NSString stringWithFormat:@"发布的专辑(%lu)", (unsigned long)self.dataAlbumArray.count];
        lable.textColor = [UIColor blackColor];
        UIButton *button = [UIButton buttonWithType:(UIButtonTypeCustom)];
        button.frame = CGRectMake(kScreenWidth - 50, 0, 40, 40);
        //    button.backgroundColor = [UIColor blackColor];
        [button setTitle:@"更多" forState:(UIControlStateNormal)];
        [button setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)];
        
//        [button setTitleColor:[UIColor lightGrayColor] forState:(UIControlStateNormal)];
        button.alpha = kAlpha;
        [button addTarget:self action:@selector(moreButton) forControlEvents:(UIControlEventTouchUpInside)];
        [view addSubview:button];
        
        if (self.dataAlbumArray.count < 2 || (self.dataAlbumArray.count == 2)) {
            button.hidden = YES;
        }

    } else {
        lable.text = [NSString stringWithFormat:@"发布的声音(%lu)", (unsigned long)self.dataVoiceArray.count];
        lable.textColor = [UIColor blackColor];
    }
    
    return view;
}
//  更多按钮的点击事件
- (void)moreButton
{
    KLSGAlbumController *albumVC = [[KLSGAlbumController alloc] init];
    albumVC.dataAlbumArray = self.dataAlbumArray;
    [self.navigationController pushViewController:albumVC animated:YES];
}
//  收藏按钮的点击事件
- (void)actionCollect:(KLSGCollectButton *)button
{
    KLSGAlbumCell *cell = (KLSGAlbumCell *)[button superview];
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    KLSGAlbumModel *model = self.dataAlbumArray[indexPath.row];
    KLSGKindModel *kindModel = [[KLSGKindModel alloc] init];
    kindModel.albumCoverUrl290 = model.coverSmall;
    kindModel.title = model.title;
    kindModel.albumId = model.albumId;
    kindModel.playsCounts = model.playTimes;
    kindModel.tracksCounts = model.tracks;
    KLSGDB *dbManager = [[KLSGDB alloc] init];
    if ([dbManager queryKindWithAlbumId:model.albumId]) {
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"已收藏" preferredStyle:(UIAlertControllerStyleAlert)];
        [self presentViewController:alertVC animated:YES completion:nil];
        [self performSelector:@selector(dismissAlertVC:) withObject:alertVC afterDelay:0.4];
    } else {
        if ([dbManager insertWithKindModel:kindModel]) {
            UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"收藏成功" preferredStyle:(UIAlertControllerStyleAlert)];
            [self presentViewController:alertVC animated:YES completion:nil];
            [self performSelector:@selector(dismissAlertVC:) withObject:alertVC afterDelay:0.4];
        } else {
            UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"不可收藏" preferredStyle:(UIAlertControllerStyleAlert)];
            [self presentViewController:alertVC animated:YES completion:nil];
            [self performSelector:@selector(dismissAlertVC:) withObject:alertVC afterDelay:0.4];
        }
    }

}

#pragma mark - alertVC
- (void)dismissAlertVC:(UIAlertController *)alertVC
{
    [alertVC dismissViewControllerAnimated:YES completion:nil];
}

- (void)setUpData
{
    
    NSURLSession *session = [NSURLSession sharedSession];
    NSString *str = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/others/ca/homePage?toUid=%@&device=android", self.uidString];
    NSURL *url = [NSURL URLWithString:str];
    NSMutableURLRequest *requset = [NSMutableURLRequest requestWithURL:url];
    self.dataDic = [NSMutableDictionary dictionary];
    __block KLSGDetailProgramAndSpeakController *mySelf = self;
    NSURLSessionDataTask *task = [session dataTaskWithRequest:requset completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (data != nil) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            [mySelf.dataDic setValue:[dic valueForKey:@"backgroundLogo"] forKey:@"backgroundLogo"];
            [mySelf.dataDic setValue:[dic valueForKey:@"backgroundLogo"] forKey:@"backgroundLogo"];
            [mySelf.dataDic setValue:[dic valueForKey:@"mobileLargeLogo"] forKey:@"mobileLargeLogo"];
            [mySelf.dataDic setValue:[dic valueForKey:@"mobileSmallLogo"] forKey:@"mobileSmallLogo"];
            [mySelf.dataDic setValue:[dic valueForKey:@"nickname"] forKey:@"nickname"];  //  昵称
            [mySelf.dataDic setValue:[dic valueForKey:@"personalSignature"] forKey:@"personalSignature"];  //  简介
            [mySelf.dataDic setValue:[dic valueForKey:@"ptitle"] forKey:@"ptitle"];  //  认证
        }
        
        [mySelf performSelectorOnMainThread:@selector(reloadData:) withObject:mySelf.tableView waitUntilDone:NO];
    }];
    [task resume];
}

- (void)reloadData:(UITableView *)tableView
{
    [self addUI];
    [tableView reloadData];
}

- (void)voiceData
{
    NSURLSession *session = [NSURLSession sharedSession];
    NSString *string = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/others/ca/track/%@/%ld/30?device=android", self.uidString, (long)_pageId];
    NSURL *url = [NSURL URLWithString:string];
    NSMutableURLRequest *requset = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];
    __block KLSGDetailProgramAndSpeakController *mySelf = self;
    NSURLSessionDataTask *task = [session dataTaskWithRequest:requset completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (data != nil) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            self.pageCount = [[dic valueForKey:@"maxPageId"] integerValue];
            NSArray *array = [dic valueForKey:@"list"];
            for (NSDictionary *d in array) {
                KLSGVoiceModel *model = [[KLSGVoiceModel alloc] init];
                [model setValuesForKeysWithDictionary:d];
                [mySelf.dataVoiceArray addObject:model];
            }
        }
        [mySelf performSelectorOnMainThread:@selector(reloadData:) withObject:mySelf.tableView waitUntilDone:NO];
    }];
    [task resume];
}

- (void)albumData
{
    NSURLSession *session = [NSURLSession sharedSession];
    NSString *string = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/others/ca/album/%@/1/30?device=android", self.uidString];
    NSURL *url = [NSURL URLWithString:string];
    NSMutableURLRequest *requset = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];
    self.dataAlbumArray = [NSMutableArray array];
    __block KLSGDetailProgramAndSpeakController *mySelf = self;
    NSURLSessionDataTask *task = [session dataTaskWithRequest:requset completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (data != nil) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSArray *array = [dic valueForKey:@"list"];
            for (NSDictionary *d in array) {
                KLSGAlbumModel *model = [[KLSGAlbumModel alloc] init];
                [model setValuesForKeysWithDictionary:d];
                [mySelf.dataAlbumArray addObject:model];
            }
        }
        [mySelf performSelectorOnMainThread:@selector(reloadData:) withObject:mySelf.tableView waitUntilDone:NO];
    }];
    [task resume];
}

- (NSMutableArray *)dataVoiceArray
{
    if (!_dataVoiceArray) {
        _dataVoiceArray = [[NSMutableArray alloc] init];
    }
    return _dataVoiceArray;
}


@end
